<style scoped>
.layui-row {
    overflow: hidden;
}

.layui-row:after,
.layui-row:before {}

.layui-form>>>.layui-form-select {
    z-index: inherit;
}

.layui-table.layui-form div {
    text-align: left;
    padding: 2px 0em 2ex 5%;
}

.table_div {
    position: relative;
    left: 150px;
    top: 0px;
    font-size: 17px;
    font-weight: bold;
}

.layui-row {
    overflow: hidden;
}

.select-item {
    width: 34.333333%;
    width: 100%;
    height: 50px;
    word-break: break-all;
    text-align: left;
}

.layui-row:after,
.layui-row:before {
    clear: none;
}

.layui-form>>>.layui-form-select {
    z-index: inherit;
}

.department>>>.layui-table td,
.layui-table th {
    padding: 9px 2px;
    white-space: nowrap;
}
</style>

<template>
<div class="organization">
    <form class="layui-form ">
        <div class="layui-col-lg4 select-item">
            <div class="layui-inline" style="width: 240px">
                <input type="text" id="searchStr" v-model="searchStr" placeholder="种植户/货运单编号/车牌号/地块名称" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 160px" id="batch">
                <!-- <select name="batchGuid" id="batchGuid" lay-filter="batchGuid" placeholder="请选择批次" class="layui-form-select">
                    <option value="" selected>请选择批次</option>
                    <option v-for="item in batchs" :value="item.guid">{{item.name}}</option>
                </select> -->
            </div>
            <div class="layui-inline" style="width: 160px" id="batchdone">
                <!-- <select name="batchGuid" id="batchGuid" lay-filter="batchGuid" placeholder="请选择批次" class="layui-form-select">
                    <option value="" selected>请选择批次</option>
                    <option v-for="item in batchs" :value="item.guid">{{item.name}}</option>
                </select> -->
            </div>
            <div class="layui-inline" style="width: 160px" id="status">
                <!--                    <select name="status"  id="status"  lay-filter="status" placeholder="请选择状态"   class="layui-form-select"   >-->
                <!--                        <option value="" selected>请选择状态</option>-->
                <!--                        <option v-for="item in statusArr" :value="item.dictkey" >{{item.dicttext}}</option>-->
                <!--                    </select>-->
            </div>
            <div class="layui-inline" style="width: 160px" id="paystatus">
                <!--                    <select name="paystatus"  id="paystatus"  lay-filter="paystatus" placeholder="请选择支付状态"   class="layui-form-select"   >-->
                <!--                        <option value="" selected>请选择支付状态</option>-->
                <!--                        <option v-for="item in paystats" :value="item.dictkey" >{{item.dicttext}}</option>-->
                <!--                    </select>-->
            </div>
            <div class="layui-inline" style="width: 160px" id="storeroomcode">
                <!--                    <select v-model="storeroomcode" name="storeroomcode" id="storeroomcode" lay-filter="storeroomcode"-->
                <!--                            placeholder="请选择库房" class="layui-form-select">-->
                <!--                        <option value="">请选择库房</option>-->
                <!--                        <option v-for="item in storeroomcodeArr" :value="item.code">{{item.name}}</option>-->
                <!--                    </select>-->
            </div>
        </div>
        <div class="layui-col-lg4 select-item">
            <div class="layui-inline" style="width: 160px">
                <input type="text" id="starttime" autocomplete="off" placeholder="请选择开始时间" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 160px">
                <input type="text" id="endtime" autocomplete="off" placeholder="请选择结束时间" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 160px">
                <input type="text" id="feedStarttime" autocomplete="off" placeholder="请选择入库起始时间" class="layui-input key">
            </div>
            <div class="layui-inline" style="width: 160px">
                <input type="text" id="feedEndtime" autocomplete="off" placeholder="请选择入库截止时间" class="layui-input key">
            </div>
            <button type="button" class="layui-btn sou" @click="search">搜索</button>
            <button type="button" class="layui-btn sou" @click="exportExcel">导出excel</button>
        </div>
    </form>
    <div style="width: 100%; overflow: auto;margin-bottom: 10px;" id="textarea">
        <table class="layui-table layui-form">
            <thead>
            <tr>
                <th>货运单编号</th>
                <th>采收工厂</th>
                <th>客户名称</th>
                <th>采收负责人</th>
                <th>采收日期</th>
                <th>品种</th>
                <th>规格</th>
                <th>结算重量(吨)</th>
                <th>入库重量(吨)</th>
                <th>单价</th>
                <th>扣杂(%)</th>
                <th>结算金额(元)</th>
                <th>订单状态</th>
                <th>支付状态</th>
                <th>入库库房</th>
                <th>入库日期</th>
                <th>承运人</th>
                <th>货运单详情</th>

            </tr>
            </thead>
            <tbody>
            <tr class="id9" v-for="(item, index) in freightorder" :key="index">
                <td  v-if="item.code">{{item.code}}</td>
                <td>{{item.csgc}}</td>
                <td>{{item.customername}}</td>
                <td>{{item.operatorname}}</td>
                <td>{{item.createtime}}</td>
                <td>{{item.variety}}</td>
                <td>{{item.specification}}</td>
                <td>{{item.settleWeight}}</td>
                <td>{{item.hweight}}</td>
                <td>{{item.price}}</td>
                <td>{{item.deductRate}}</td>
                <td>{{item.settleAmount}}</td>
                <td>{{item.orderstatus}}</td>
                <td>{{item.paystatusname}}</td>
                <td>{{item.storename}}</td>
                <td>{{item.instoredate}}</td>
                <td>{{item.drivername}} {{item.driverphone}} {{item.carcode}}</td>
                <td><a href="javascript:;" @click="GetInfo(item.guid)">货运单详情</a></td>
            </tr>
            <tr v-if="freightorder.length != 0">
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td>合计：{{totalData.settleWeight}}</td>
                <td></td>
                <td></td>
                <td>合计：{{totalData.settleAmount}}</td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            </tbody>
        </table>
    </div>

    <Pagination :cur="currentPage" :all="totalPage" :callback="turnPage"></Pagination>
    <div style="height: 200px"></div>

</div>
</template>

<script>
import Pagination from '../common/Pagination.vue'
let qs = require('qs');
export default {
    name: 'FreightorderExport',
    components: {
        Pagination
    },
    props: ['id'],
    data() {
        return {
            guid: this.id,
            organizations: [],
            currentPage: 1,
            totalPage: 0,
            searchName: '',
            batchs: [],
            batchGuid: '',
            freightorder: [],
            storeroom: [],
            statusArr: [],
            status: '',
            storeroomcodeArr: [],
            storeroomcode: '',
            fstatus: '',
            starttime: '',
            endtime: '',
            searchStr: '',
            paystats: [],
            totalData: '',
            feedStarttime: '',
            feedEndtime: '',
            falg :false,
            //采收中的批次
            batch: [],
            //完成的批次
            batchdone: [],
            pbguids: []
        }
    },
    updated: function () {
        layui.form.render('select');
        layui.form.render();
    },
    mounted() {
        let that = this;
        this.getBatches();
        that.getBaseInfo();
        //that.getPageData()
        this.starttime = this.getNowMonthDate();
        this.endtime = this.getDate();
        layui.use(['form', 'laydate'], function () {
            var form = layui.form,
                layer = layui.layer;
            var laydate = layui.laydate;

            //执行一个laydate实例
            laydate.render({
                elem: '#starttime', //指定元素
                value: that.getNowMonthDate()
            });
            laydate.render({
                elem: '#endtime',
                value: that.getDate()
            });
            laydate.render({
                elem: '#feedStarttime',
                //value: that.getNowMonthDate()
            });
            laydate.render({
                elem: '#feedEndtime',
                //value: that.getDate(-1)
            });

            layui.form.render();
        });
        this.getPaystatus();
    },
    methods: {
        GetInfo(row) {
            this.$parent.guid = row;
            this.$parent.switchPage('FreightorderForder');
        },
        getPaystatus: function () {
            let that = this;
            this.axios({
                method: 'get',
                responseType: 'json',
                url: '/sales/Sellform!findDict.action',
                params: {
                    type: 90
                }
            }).then(response => {
                if (response.statusText == "OK") {

                    that.paystats = response.data;
                    //支付状态多选
                    this.initPaystatusSelect();
                } else {
                    this.toastText('获取支付状态数据失败');
                }
            });
        },
        search: function () {
            this.getPageData('search');
        },
        turnPage: function (data) {
            this.currentPage = data;
            this.getPageData();
        },
        getPageData: function (type = '') {
            if (this.dateToValue($('#endtime').val()) < this.dateToValue($('#starttime').val())) {
                this.toastText('结束时间须大于起始时间！');
                return;
            }
            if (this.dateToValue($('#feedEndtime').val()) < this.dateToValue($('#feedStarttime').val())) {
                this.toastText('入库截止时间须大于入库起始时间！');
                return;
            }
            let that = this;

            let postData = that.getSubmitData(type);



            if(this.falg){
                let loader = layui.layer.load();
                $.ajax({
                    url: '/harvest/FreightorderExport!getFreightorderData.action',
                    type: "post",
                    data: postData,
                    async: true,
                    dataType: "json",
                    success: function (res) {
                        if (res.page != undefined && res.page != undefined) {
                            //分页数据赋值
                            that.currentPage = res.page.indexPage;
                            that.totalPage = res.page.pageCount;
                            that.freightorder = res.page.rows;
                            console.log("货运单信息", that.freightorder)
                            that.totalData = res.sum || '';
                        } else {
                            that.alert("系统错误");
                        }
                    },
                    complete: function () {
                        layer.close(loader);
                        $('#textarea').css('max-height', $(window).height() - $('#textarea').offset().top - 10)
                    }
                });
            }


        },
        /**
         * 查询权限内所有选项的数据
         * @param guid  选择框内选项
         * @param entitys 选择框内所有枚举值
         */
        selectPermisAll: function (entitys, description) {
            if (entitys.length == 0) {
                this.toast(description);
                return false;
            }

            var srguids = [];
            $.each(entitys, function (index, entity) {
                srguids.push(entity.guid)
            });
            return srguids.toString();
        },

        getTypeName: function (type) {

            let name = '';
            switch (type) {
                case '1':
                    name = '采收入库';
                    break;
                case '2':
                    name = '地头直销';
                    break;

            }
            return name;
        },
        exportExcel: function () {
            if (this.dateToValue($('#endtime').val()) < this.dateToValue($('#starttime').val())) {
                this.toastText('结束时间须大于起始时间！');
                return;
            }
            if (this.dateToValue($('#feedEndtime').val()) <= this.dateToValue($('#feedStarttime').val())) {
                this.toastText('入库截止时间须大于入库起始时间！');
                return;
            }

            let postData = this.getSubmitData('search');
            // var optionAll = this.selectPermisAll(this.batchGuid, this.batchs, "无授权批次!");
            // if (optionAll) {
            //     postData.pbguids = optionAll;
            // }
            let queryStr = qs.stringify(postData);
            if(this.falg){
                window.location.href = "/harvest/FreightorderExport!exportData.action?" + queryStr;
            }

            // window.location.href="/harvest/FreightorderExport!exportData.action?startTime=" + postData.startTime + "&endTime=" + postData.endTime + "&batchGuid=" + postData.batchGuid + "&searchStr=" + postData.searchStr + "&rows=" + this.total +  "&page=1&pbguids="+postData.pbguids+'&statusStr=' + postData.statusStr;
        },
        getBaseInfo: function (id) {
            this.$post('/harvest/Print!getFreightorderBaseInfo.action')
                .then(response => {
                    let data = response.data;
                    if (data.msg == 'success') {
                        // this.batchs = data.batchs;
                        this.statusArr = data.dicts;

                        this.storeroomcodeArr = data.storeroomcodeArr;
                        //状态多选
                        this.initStatusSelect();
                        //库房多选
                        this.initRoomsSelect();
                    } else {
                        this.toast('获取基础信息失败！');
                    }
                })
        },
        getBatches: function () {
            let that = this;
            this.axios({
                method: 'get',
                url: '/harvest/Procurementbatch!findBatchbyFun.action',
                params: {
                    functiontype: 20,
                }
            }).then(response => {
                if (response.data.msg == 'success') {
                    that.batchs = response.data.batchs;
                    if(that.batchs.length != 0){
                        $.each(that.batchs, function (index, entity) {
                             if(entity.status == 2){
                                 that.batchdone.push(entity)
                             }else{
                                 that.batch.push(entity)
                             }
                        });
                        that.falg = true;
                    } else {
                        that.toastText('没有授权批次')
                    }
                    that.initBatchsSelect();
                    that.initBatchsdoneSelect();
                } else {
                    that.toastText('获取批次数据失败')
                }
            });
        },
        initStatusSelect: function () {
            layui.xmSelect.render({
                el: '#status',
                tips: '请选择状态',
                name: 'status',
                prop: {
                    name: 'dicttext',
                    value: 'dictkey'
                },
                data: this.statusArr
            })
        },
        initPaystatusSelect: function () {
            layui.xmSelect.render({
                el: '#paystatus',
                tips: '请选择支付状态',
                name: 'paystatus',
                prop: {
                    name: 'dicttext',
                    value: 'dictkey'
                },
                data: this.paystats
            })
        },
        initRoomsSelect: function () {
            layui.xmSelect.render({
                el: '#storeroomcode',
                tips: '请选择库房',
                name: 'storeroomcode',
                prop: {
                    name: 'name',
                    value: 'guid'
                },
                data: this.storeroomcodeArr
            })
        },
        initBatchsSelect: function () {
            layui.xmSelect.render({
                el: '#batch',
                tips: '请选择采收中批次',
                name: 'batch',
                prop: {
                    name: 'name',
                    value: 'guid'
                },
                data: this.batch
            })
        },
        initBatchsdoneSelect: function () {
            layui.xmSelect.render({
                el: '#batchdone',
                tips: '请选择采收完成批次',
                name: 'batchdone',
                prop: {
                    name: 'name',
                    value: 'guid'
                },
                data: this.batchdone
            })
        },
        //获取当前日期
        getDate: function (dayCount = 0) {
            var dd = new Date();
            dd.setDate(dd.getDate() + dayCount); //设置日期
            var y = dd.getFullYear();
            var m = dd.getMonth() + 1; //获取当前月份的日期
            var fullM = m.length == 2 ? m : '0' + m;
            var d = dd.getDate();
            return y + "-" + fullM + "-" + d;
        },
        //获取本月第一天
        getNowMonthDate: function () {
            var date = new Date();
            var year = date.getFullYear() + "";
            var month = (date.getMonth() + 1) + "";
            // 本月第一天日期
            var begin = year + "-" + month + "-01"
            return begin;
        },
        getCheckedValue: function (emeName) {
            var ids = new Array();
            $('input[name="' + emeName + '"]:checked').each(function () {
                ids.push($(this).val());
            });
            return ids;
        },
        getSubmitData(type) {
            let postData = {};
            this.pbguids = [];
            if (type != 'search') {
                postData.page = this.currentPage;
            }
            this.starttime = $('#starttime').val();
            this.feedStarttime = $('#feedStarttime').val();
            this.endtime = $('#endtime').val();
            this.feedEndtime = $('#feedEndtime').val();
            this.batchGuid = $("#batchGuid option:selected").val();
            this.searchStr = $('#searchStr').val();

            var status = this.getCheckedValue('status');
            postData.startTime = this.starttime;
            postData.startrcTime = this.feedStarttime;
            postData.endTime = this.endtime;
            postData.endrcTime = this.feedEndtime;
            postData.batchGuid = this.batchGuid;
            postData.searchStr = this.searchStr;

            postData.statusStr = $("input[name='status']").val();
            postData.paystatusStr = $("input[name='paystatus']").val();
            if ($("input[name='storeroomcode']").val() != '') {
                postData.storeroomguidArr = $("input[name='storeroomcode']").val();
            }
            if ($("input[name='batch']").val() != '') {
                this.pbguids.push($("input[name='batch']").val());
            }
            if ($("input[name='batchdone']").val() != '') {
                this.pbguids.push($("input[name='batchdone']").val());
            }

            if(this.pbguids == null || this.pbguids == ""){
                var optionAll = this.selectPermisAll(this.batchs, "无授权批次!");
                if (optionAll) {
                    postData.pbguids = optionAll;
                }
            }else{
                postData.pbguids = this.pbguids.toString();
            }




            //多选下拉跨
            //postData.statusStr =  this.loadCheckValue($('.layui-this'));
            //  postData.statusStr = $('input[name="tag_ids2"]').val();

            return postData;
        },
        loadStatusData: function (startsArr) {
            let that = this;
            var arr = [];
            $.each(startsArr, function (index, item) {
                var itemData = {
                    'id': item.dictkey,
                    'name': item.dicttext,
                    'status': item.isenable
                };
                arr.push(itemData)
            });
            layui.use(['layer', 'form', 'jquery'], function () {
                $ = layui.jquery;
                var form = layui.form,
                    selectM = layui.selectM;
                var tagIns1 = selectM({
                    //元素容器【必填】
                    elem: '#tag_ids2'
                        //候选数据【必填】
                        ,
                    data: arr,
                    max: that.statusArr.length,
                    width: 600
                        //添加验证
                        ,
                    verify: 'required',
                    tips: '请选择状态 最多 {max} 个',
                });

            });

        },
        loadCheckValue: function (status) {
            var arr = [];
            $.each(status, function (index, item) {
                arr.push($(item).attr('lay-value'))
            });
            return arr.toString();
        }

    }

}
</script>
